package com.woniuxy.woniuticket.movieinfomodule.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Utopia
 * @title: FileInterceptor
 * @projectName woniuticket
 * @description: TODO
 * @date 2019/6/17 16:06
 */

@Component
public class FileInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        boolean flag = true;
        if (request instanceof MultipartHttpServletRequest){
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = fileRequest.getFileMap();
            Iterator<String> iterator = files.keySet().iterator();
            while (iterator.hasNext()){
                String key = iterator.next();
                MultipartFile file = files.get(key);
                if (!checkType(file.getOriginalFilename())){
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    private boolean checkType(String fileName) {
        String type = "png,jpg,jpeg,mp4";
        String[] types = type.split(",");
        for (String str: types) {
            if (fileName.endsWith(str)){
                return true;
            }
        }
        return false;
    }
}
